package beautiful.butterfly.server.nettyserver;

import beautiful.butterfly.server.nettyserver.marshalling.MarshallingCodeCFactory;
import beautiful.butterfly.server.nettyserver.marshalling.ServerHandler;
import beautiful.butterfly.server.nettyserver.task.ITask;
import beautiful.butterfly.server.nettyserver.task.TaskMap;
import beautiful.butterfly.server.nettyserver.task.impl.HeartBeat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


public class Server {
    private static final Logger log = LoggerFactory.getLogger(Server.class);

    public static void buildTaskMap() {

        Map<Long, ITask> taskMap = TaskMap.taskMap.get(1l);
        if (taskMap == null) {
            taskMap = new HashMap<Long, ITask>();
        }
        TaskMap.taskMap.put(1l, taskMap);
        taskMap.put(1l, new HeartBeat());

    }

    public static void main(String[] args) throws Exception {
        //构建task关系

        Server.buildTaskMap();


        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        new Server().bind(port);
    }

    public void bind(int port) throws Exception {
        // 配置服务端的NIO线程组
        EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup();
        EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossEventLoopGroup, workerEventLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel socketChannel) {
                            socketChannel.pipeline().addLast(
                                    MarshallingCodeCFactory
                                            .buildMarshallingDecoder());
                            socketChannel.pipeline().addLast(
                                    MarshallingCodeCFactory
                                            .buildMarshallingEncoder());
                            socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    });

            // 绑定端口，同步等待成功
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

            // 等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 优雅退出，释放线程池资源
            bossEventLoopGroup.shutdownGracefully();
            workerEventLoopGroup.shutdownGracefully();
        }
    }
}
